package com.fifth.apartment.config;

import com.fifth.apartment.entity.User;
import com.fifth.apartment.mapper.UserMapper;
import com.fifth.apartment.utils.MobileUtil;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Objects;

@Service
@Slf4j
public class SpringSecurityDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Transactional
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            log.info("UserDetailsService没有接收到用户账号");
            throw new UsernameNotFoundException("UserDetailsService没有接收到用户账号");
        } else {
            //根据用户名查找用户信息
            User user = null;
            if (MobileUtil.isMobileNO(username)) {
                //手机号验证码登陆
                user = userMapper.selectUserByPhone(username);

            } else {
                //用户名, 密码登陆
                user = userMapper.selectUserByName(username);
            }
            if (user == null) {
                throw new UsernameNotFoundException(String.format("用户不存在", username));
            }
            LoginUser loginUser = new LoginUser(user);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            return loginUser;
        }
    }
}
